package com.yzf.enterprise.common.utils.file;


import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author AKing31
 * @version 1.0
 * @create 2020-02-14 08:55 PM
 */
@Slf4j
public class EasyExcelUtils {

    private EasyExcelUtils() {
    }

    /**
     * 导出excel 支持一张表导出多个sheet
     *
     * @param response             输出流
     * @param sheetNameAndDateList Map<String, List>  sheetName和每个sheet的数据
     * @param type                 ExcelTypeEnum 要导出的excel的类型 有ExcelTypeEnum.xls 和有ExcelTypeEnum.xlsx
     * @param fileName             文件名称
     * @throws UnsupportedEncodingException 异常
     */
    public static void createExcelByEasyExcel(HttpServletResponse response, Map<String, List<? extends BaseRowModel>> sheetNameAndDateList, ExcelTypeEnum type, String fileName) throws UnsupportedEncodingException {
        try {
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + type.getValue());
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            ServletOutputStream out = response.getOutputStream();
            //ExcelWriter writer = new ExcelWriter(null, out, type, true, new StyleExcelHandler());
            ExcelWriter writer = new ExcelWriter(out, type, true);
            setSheet(sheetNameAndDateList, writer);
            writer.finish();
            out.flush();
        } catch (IOException e) {
            log.error("导出{}失败", fileName, e);
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            try {
                response.getWriter().println(JSON.toJSONString(map));
            } catch (IOException ex) {
                log.error("导出{}失败", fileName, e);
            }
        }
    }


    /**
     * @Author laixiaoxing
     * @Description //setSheet数据
     * @Date 上午12:39 2019/1/31
     */
    private static void setSheet(Map<String, List<? extends BaseRowModel>> sheetNameAndDateList, ExcelWriter writer) {
        int sheetNum = 1;
        for (Map.Entry<String, List<? extends BaseRowModel>> stringListEntry : sheetNameAndDateList.entrySet()) {
            Map<Integer, Integer> columnWidth = new HashMap();

            Class<? extends BaseRowModel> aClass = stringListEntry.getValue().get(0).getClass();
            int cellNum = aClass.getDeclaredFields().length;
            for (int i = 0; i < cellNum; i++) {
                columnWidth.put(i, 8000);
            }
            Sheet sheet = new Sheet(sheetNum, 0, aClass);
            sheet.setSheetName(stringListEntry.getKey());
            sheet.setColumnWidthMap(columnWidth);
            //sheet.setAutoWidth(true);
            writer.write(stringListEntry.getValue(), sheet);
            sheetNum++;
        }
    }
}

